<template>
  <div class="purchase-order-detail">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <div class="header-left">
        <h2>采购订单详情</h2>
        <div class="order-title">{{ purchaseOrder?.orderSubject }}</div>
        <div class="order-meta">
          <span>创建人: {{ purchaseOrder?.createdByName || '未知' }}</span>
          <span>创建时间: {{ formatDateTime(purchaseOrder?.createdAt) }}</span>
          <span v-if="purchaseOrder?.lastModifiedByName">最后修改人: {{ purchaseOrder.lastModifiedByName }}</span>
          <span v-if="purchaseOrder?.lastModifiedAt">修改时间: {{ formatDateTime(purchaseOrder.lastModifiedAt) }}</span>
        </div>
      </div>
      <div class="header-right">
        <div class="action-buttons">
          <el-button
            @click="handleBack"
            icon="ArrowLeft"
          >
            返回列表
          </el-button>
          <el-button
            v-if="canEdit"
            type="warning"
            @click="handleEdit"
            icon="Edit"
          >
            编辑
          </el-button>
          <el-button
            v-if="canDelete"
            type="danger"
            @click="handleDelete"
            icon="Delete"
          >
            删除
          </el-button>
          <el-button
            v-if="canCopy"
            type="info"
            @click="handleCopy"
            icon="CopyDocument"
          >
            复制
          </el-button>
          <el-button
            type="primary"
            @click="handlePrint"
            icon="Printer"
          >
            打印
          </el-button>
          <el-button
            type="warning"
            @click="exportDetailPdf"
            icon="Document"
          >
            导出PDF
          </el-button>
          <el-button
            v-if="canSubmit"
            type="success"
            @click="handleSubmit"
            icon="Check"
          >
            √ 提交
          </el-button>
          <el-button v-if="purchaseOrder?.orderStatus==='待审批'" type="success" @click="approveDialogVisible=true">同意</el-button>
          <el-button v-if="purchaseOrder?.orderStatus==='待审批'" type="danger" @click="rejectDialogVisible=true">驳回</el-button>
          <el-button
            type="info"
            @click="testApi"
            icon="Refresh"
          >
            测试API
          </el-button>
        </div>
        <div class="status-indicator">
          <div class="status-stamp">{{ statusStampText }}</div>
        </div>
      </div>
    </div>

    <!-- 状态提示信息 -->
    <div v-if="statusHint" class="status-hint">
      <el-alert
        :title="statusHint.title"
        :description="statusHint.description"
        :type="statusHint.type"
        show-icon
        :closable="false"
      />
    </div>

    <!-- 导航标签页 -->
    <el-tabs v-model="activeTab" class="detail-tabs">
      <el-tab-pane label="订单信息" name="order-info">
        <!-- 基础信息 -->
        <div class="info-section">
          <h3 class="section-title">基础信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <label>采购单号:</label>
                <span>{{ purchaseOrder?.purchaseOrderNumber }}</span>
              </div>
              <div class="info-item">
                <label>采购日期:</label>
                <span>{{ formatDate(purchaseOrder?.purchaseDate?.toString()) }}</span>
              </div>
              <div class="info-item">
                <label>联系人:</label>
                <span>{{ purchaseOrder?.contactPerson || '-' }}</span>
              </div>
              <div class="info-item">
                <label>采购部门:</label>
                <span>{{ purchaseOrder?.purchasingDepartmentName }}</span>
              </div>
              <div class="info-item">
                <label>联系方式:</label>
                <span>{{ purchaseOrder?.contactMethod || '-' }}</span>
              </div>
              <div class="info-item">
                <label>结算方式:</label>
                <span>{{ getSettlementMethodText(purchaseOrder?.settlementMethod) }}</span>
              </div>
              <div class="info-item">
                <label>备注:</label>
                <span>{{ purchaseOrder?.remarks || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>订单主题:</label>
                <span>{{ purchaseOrder?.orderSubject }}</span>
              </div>
                      <div class="info-item">
          <label>关联销售订单:</label>
          <span>{{ purchaseOrder?.relatedSalesOrder || '-' }}</span>
        </div>
        <div class="info-item">
          <label>关联请购单:</label>
          <span>{{ purchaseOrder?.relatedPurchaseRequest || '-' }}</span>
        </div>
              <div class="info-item">
                <label>供应商名称:</label>
                <span>{{ purchaseOrder?.supplierName }}</span>
              </div>
              <div class="info-item">
                <label>联系电话:</label>
                <span>{{ purchaseOrder?.contactPhone || '-' }}</span>
              </div>
              <div class="info-item">
                <label>采购人员:</label>
                <span>{{ purchaseOrder?.purchaserName }}</span>
              </div>
              <div class="info-item">
                <label>关联项目:</label>
                <span>{{ purchaseOrder?.relatedProjectName || '-' }}</span>
              </div>
              <div class="info-item">
                <label>交付地址:</label>
                <span>{{ purchaseOrder?.deliveryAddress || '-' }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 物品明细 -->
        <div class="info-section">
          <h3 class="section-title">物品明细</h3>
          <div class="detail-actions">
            <el-button type="success" @click="handleExport" icon="Download">
              导出
            </el-button>
          </div>
          <el-table
            :data="purchaseOrder?.details || []"
            border
            style="width: 100%"
            show-summary
            :summary-method="getDetailSummary"
          >
            <el-table-column prop="serialNumber" label="序号" width="60" />
            <el-table-column prop="itemNumber" label="物品编号" width="150" />
            <el-table-column prop="itemName" label="物品名称" min-width="150" />
            <el-table-column prop="specificationModel" label="规格型号" width="120" />
            <el-table-column prop="unit" label="单位" width="100" />
            <el-table-column prop="brand" label="品牌" width="120" />
            <el-table-column prop="purchaseQuantity" label="采购数量" width="100" />
            <el-table-column prop="mainUnitQuantity" label="主单位数量" width="120" />
            <el-table-column prop="taxRate" label="税率" width="80">
              <template #default="scope">
                {{ scope.row.taxRate }}%
              </template>
            </el-table-column>
            <el-table-column prop="unitPriceIncludingTax" label="含税单价" width="120">
              <template #default="scope">
                {{ formatCurrency(scope.row.unitPriceIncludingTax) }}
              </template>
            </el-table-column>
            <el-table-column prop="amountIncludingTax" label="含税金额" width="120">
              <template #default="scope">
                {{ formatCurrency(scope.row.amountIncludingTax) }}
              </template>
            </el-table-column>
          </el-table>
          <div class="detail-summary">
            <span class="summary-item">总量: {{ totalQuantity }}</span>
            <span class="summary-item">总金额: {{ formatCurrency(totalAmount) }}</span>
          </div>
        </div>

        <!-- 附件 -->
        <div class="info-section">
          <h3 class="section-title">附件</h3>
          <div v-if="purchaseOrder?.attachments && purchaseOrder.attachments.length > 0" class="attachment-list">
            <div
              v-for="attachment in purchaseOrder.attachments"
              :key="attachment.id"
              class="attachment-item"
            >
              <div class="attachment-info">
                <div class="file-name">{{ attachment.fileName }}</div>
                <div class="file-size">{{ formatFileSize(attachment.fileSize) }}</div>
                <div class="upload-time">{{ formatDateTime(attachment.uploadTime) }}</div>
              </div>
              <div class="attachment-actions">
                <el-button type="primary" link @click="previewAttachment(attachment)">查看</el-button>
                <el-button type="primary" link @click="downloadAttachment(attachment)">
                  下载
                </el-button>
                <el-button type="danger" link @click="deleteAttachment(attachment)">
                  删除
                </el-button>
              </div>
            </div>
          </div>
          <div v-else class="no-attachments">
            暂无附件
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="入库记录" name="inbound-record">
        <div class="tab-content">
          <div class="info-section">
            <div class="detail-actions">
              <el-button type="success" @click="handleExport" icon="Download">导出</el-button>
            </div>
            <el-table :data="inboundRecords" border stripe v-loading="tabLoading">
              <el-table-column type="selection" width="55" />
              <el-table-column prop="inboundOrderNumber" label="入库单号" width="160" />
              <el-table-column prop="inboundOrderSubject" label="入库订单主题" min-width="220" />
              <el-table-column prop="inboundDate" label="入库日期" width="120">
                <template #default="scope">{{ formatDate(scope.row.inboundDate) }}</template>
              </el-table-column>
              <el-table-column prop="inboundType" label="入库类型" width="120" />
              <el-table-column prop="supplierName" label="供应商" width="160" />
              <el-table-column prop="totalInboundQuantity" label="入库总量" width="100" />
              <el-table-column prop="inboundAmount" label="入库金额" width="120">
                <template #default="scope">{{ formatCurrency(scope.row.inboundAmount) }}</template>
              </el-table-column>
              <el-table-column prop="inboundPersonnelName" label="入库人" width="120" />
              <el-table-column label="操作" width="100" fixed="right">
                <template #default>
                  <el-button link type="primary">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <div class="pagination-info">共 {{ inboundTotal }} 项数据</div>
              <el-pagination
                v-model:current-page="inboundPageIndex"
                v-model:page-size="inboundPageSize"
                :page-sizes="[5,10,20,50]"
                :total="inboundTotal"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="() => loadInboundRecords(1)"
                @current-change="(p:number) => loadInboundRecords(p)"
              />
            </div>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="付款记录" name="payment-record">
        <div class="tab-content">
          <div class="info-section">
            <el-table :data="paymentRecords" border stripe v-loading="tabLoading">
              <el-table-column type="selection" width="55" />
              <el-table-column prop="paymentNumber" label="支出单号" width="160" />
              <el-table-column prop="paymentSubject" label="支出主题" min-width="220" />
              <el-table-column prop="paymentDate" label="支付日期" width="120">
                <template #default="scope">{{ formatDate(scope.row.paymentDate) }}</template>
              </el-table-column>
              <el-table-column prop="payee" label="收款方" width="160" />
              <el-table-column prop="paymentAmount" label="付款金额" width="120">
                <template #default="scope">{{ formatCurrency(scope.row.paymentAmount) }}</template>
              </el-table-column>
              <el-table-column prop="bankAccountNumber" label="银行账号" width="180" />
              <el-table-column label="操作" width="100" fixed="right">
                <template #default>
                  <el-button link type="primary">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <div class="pagination-info">共 {{ paymentTotal }} 项数据</div>
              <el-pagination
                v-model:current-page="paymentPageIndex"
                v-model:page-size="paymentPageSize"
                :page-sizes="[5,10,20,50]"
                :total="paymentTotal"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="() => loadPaymentRecords(1)"
                @current-change="(p:number) => loadPaymentRecords(p)"
              />
            </div>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="到票记录" name="invoice-record">
        <div class="tab-content">
          <div class="info-section">
            <el-table :data="invoiceRecords" border stripe v-loading="tabLoading">
              <el-table-column type="selection" width="55" />
              <el-table-column prop="invoiceNumber" label="到票编号" width="160" />
              <el-table-column prop="invoiceSubject" label="到票主题" min-width="220" />
              <el-table-column prop="invoiceDate" label="到票日期" width="120">
                <template #default="scope">{{ formatDate(scope.row.invoiceDate) }}</template>
              </el-table-column>
              <el-table-column prop="issuer" label="开票方" width="160" />
              <el-table-column prop="invoiceType" label="发票类型" width="120" />
              <el-table-column prop="invoiceCode" label="发票编码" width="140" />
              <el-table-column label="操作" width="100" fixed="right">
                <template #default>
                  <el-button link type="primary">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <div class="pagination-info">共 {{ invoiceTotal }} 项数据</div>
              <el-pagination
                v-model:current-page="invoicePageIndex"
                v-model:page-size="invoicePageSize"
                :page-sizes="[5,10,20,50]"
                :total="invoiceTotal"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="() => loadInvoiceRecords(1)"
                @current-change="(p:number) => loadInvoiceRecords(p)"
              />
            </div>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="检验记录" name="inspection-record">
        <div class="tab-content">
          <div class="info-section">
            <el-table :data="inspectionRecords" border stripe v-loading="tabLoading">
              <el-table-column type="selection" width="55" />
              <el-table-column prop="inspectionNumber" label="检验单号" width="160" />
              <el-table-column prop="inspectionSubject" label="检验主题" min-width="220" />
              <el-table-column prop="inspectionDate" label="检验日期" width="120">
                <template #default="scope">{{ formatDate(scope.row.inspectionDate) }}</template>
              </el-table-column>
              <el-table-column prop="inspector" label="检验人" width="120" />
              <el-table-column label="物品概要" min-width="180">
                <template #default="scope">
                  <el-tooltip :content="scope.row.itemsSummary || '-'" placement="top" :show-after="500">
                    <span>{{ scope.row.itemsSummary || '-' }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column prop="remarks" label="备注" min-width="160" />
              <el-table-column label="操作" width="100" fixed="right">
                <template #default>
                  <el-button link type="primary">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <div class="pagination-info">共 {{ inspectionTotal }} 项数据</div>
              <el-pagination
                v-model:current-page="inspectionPageIndex"
                v-model:page-size="inspectionPageSize"
                :page-sizes="[5,10,20,50]"
                :total="inspectionTotal"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="() => loadInspectionRecords(1)"
                @current-change="(p:number) => loadInspectionRecords(p)"
              />
            </div>
            <div style="margin-top:12px;text-align:right">
              <el-button type="primary" @click="gotoIncomingInspectionList">新增到货检验</el-button>
            </div>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="退货记录" name="return-record">
        <div class="tab-content">
          <div class="info-section">
            <el-table :data="returnRecords" border stripe v-loading="tabLoading">
              <el-table-column type="selection" width="55" />
              <el-table-column prop="outboundNumber" label="出库单号" width="160" />
              <el-table-column prop="outboundSubject" label="出库订单主题" min-width="220" />
              <el-table-column prop="outboundDate" label="出库日期" width="120">
                <template #default="scope">{{ formatDate(scope.row.outboundDate) }}</template>
              </el-table-column>
              <el-table-column prop="outboundType" label="出库类型" width="120" />
              <el-table-column prop="supplierName" label="供应商" width="160" />
              <el-table-column prop="totalOutboundQuantity" label="出库总量" width="100" />
              <el-table-column prop="outboundAmount" label="出库金额" width="120">
                <template #default="scope">{{ formatCurrency(scope.row.outboundAmount) }}</template>
              </el-table-column>
              <el-table-column label="操作" width="100" fixed="right">
                <template #default>
                  <el-button link type="primary">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <div class="pagination-info">共 {{ returnTotal }} 项数据</div>
              <el-pagination
                v-model:current-page="returnPageIndex"
                v-model:page-size="returnPageSize"
                :page-sizes="[5,10,20,50]"
                :total="returnTotal"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="() => loadReturnRecords(1)"
                @current-change="(p:number) => loadReturnRecords(p)"
              />
            </div>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="审批记录" name="approval-record">
        <div class="tab-content">
          <div class="info-section">
            <el-steps :active="approvalActiveIndex" finish-status="success">
              <el-step v-for="(n,idx) in approvalFlowNodes" :key="idx" :title="n" />
            </el-steps>
          </div>
          <div class="info-section">
            <el-table :data="approvalSteps" border stripe v-loading="tabLoading">
              <el-table-column label="序号" width="60">
                <template #default="scope">{{ scope.$index + 1 }}</template>
              </el-table-column>
              <el-table-column prop="nodeName" label="节点" width="200" />
              <el-table-column prop="handlerName" label="办理人员" width="140" />
              <el-table-column prop="status" label="状态" width="120" />
              <el-table-column prop="receivedAt" label="接收时间" width="180">
                <template #default="scope">{{ formatDateTime(scope.row.receivedAt) }}</template>
              </el-table-column>
              <el-table-column prop="submittedAt" label="提交时间" width="180">
                <template #default="scope">{{ formatDateTime(scope.row.submittedAt) }}</template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="操作记录" name="operation-record">
        <div class="tab-content">
          <div class="info-section">
            <el-table :data="operationRecords" border stripe v-loading="tabLoading">
              <el-table-column type="selection" width="55" />
              <el-table-column prop="operatorName" label="操作人" width="140" />
              <el-table-column prop="operationTime" label="操作时间" width="180">
                <template #default="scope">{{ formatDateTime(scope.row.operationTime) }}</template>
              </el-table-column>
              <el-table-column prop="operationContent" label="操作内容" min-width="300" />
            </el-table>
            <div class="pagination-container">
              <div class="pagination-info">共 {{ operationTotal }} 项数据</div>
              <el-pagination
                v-model:current-page="operationPageIndex"
                v-model:page-size="operationPageSize"
                :page-sizes="[5,10,20,50]"
                :total="operationTotal"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="() => loadOperationRecords(1)"
                @current-change="(p:number) => loadOperationRecords(p)"
              />
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 编辑对话框 -->
    <PurchaseOrderForm
      v-model:visible="formVisible"
      :purchase-order="purchaseOrder"
      :is-edit="true"
      @success="handleFormSuccess"
    />

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="400px"
    >
      <p>确定要删除采购订单 "{{ purchaseOrder?.orderSubject }}" 吗？</p>
      <p class="text-danger">删除后无法恢复！</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog v-model="approveDialogVisible" title="审批通过" width="420px">
      <el-input type="textarea" v-model="approveComments" placeholder="审批意见（可选）" rows="4" />
      <template #footer>
        <el-button @click="approveDialogVisible=false">取消</el-button>
        <el-button type="success" @click="confirmApprove">同意</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="rejectDialogVisible" title="审批驳回" width="480px">
      <el-input type="textarea" v-model="rejectReason" placeholder="驳回原因（可选）" rows="4" />
      <el-checkbox v-model="rejectToPreviousLevel">驳回到上一级</el-checkbox>
      <el-checkbox v-model="rejectToApplicant">驳回到申请人</el-checkbox>
      <template #footer>
        <el-button @click="rejectDialogVisible=false">取消</el-button>
        <el-button type="danger" @click="confirmReject">驳回</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { purchaseOrderApi } from '@/api/purchaseOrderApi'
import type {
  PurchaseOrderDetailDto,
  InboundRecordRow,
  PaymentRecordRow,
  InvoiceRecordRow,
  InspectionRecordRow,
  ReturnRecordRow,
  ApprovalStepRow,
  OperationRecordRow
} from '@/types/purchaseOrder'
import PurchaseOrderForm from './PurchaseOrderForm.vue'
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'

// 路由
const route = useRoute()
const router = useRouter()

// 响应式数据
const purchaseOrder = ref<PurchaseOrderDetailDto | null>(null)
const loading = ref(false)
const activeTab = ref('order-info')
const formVisible = ref(false)
const deleteDialogVisible = ref(false)

// 详情各记录 Tab 状态
const tabLoading = ref(false)

// 入库
const inboundRecords = ref<InboundRecordRow[]>([])
const inboundPageIndex = ref(1)
const inboundPageSize = ref(5)
const inboundTotal = ref(0)

// 付款
const paymentRecords = ref<PaymentRecordRow[]>([])
const paymentPageIndex = ref(1)
const paymentPageSize = ref(5)
const paymentTotal = ref(0)

// 到票
const invoiceRecords = ref<InvoiceRecordRow[]>([])
const invoicePageIndex = ref(1)
const invoicePageSize = ref(5)
const invoiceTotal = ref(0)

// 检验
const inspectionRecords = ref<InspectionRecordRow[]>([])
const inspectionPageIndex = ref(1)
const inspectionPageSize = ref(5)
const inspectionTotal = ref(0)

// 退货
const returnRecords = ref<ReturnRecordRow[]>([])
const returnPageIndex = ref(1)
const returnPageSize = ref(5)
const returnTotal = ref(0)

// 审批
const approvalFlowNodes = ref<string[]>([])
const approvalSteps = ref<ApprovalStepRow[]>([])
const approvalActiveIndex = ref(1)

// 操作
const operationRecords = ref<OperationRecordRow[]>([])
const operationPageIndex = ref(1)
const operationPageSize = ref(5)
const operationTotal = ref(0)

// 计算属性
const totalQuantity = computed(() => {
  return purchaseOrder.value?.details?.reduce((sum, item) => sum + (item.purchaseQuantity || 0), 0) || 0
})

const totalAmount = computed(() => {
  return purchaseOrder.value?.details?.reduce((sum, item) => sum + (item.amountIncludingTax || 0), 0) || 0
})

const canEdit = computed(() => {
  return purchaseOrder.value?.orderStatus === '草稿'
})

const canDelete = computed(() => {
  return purchaseOrder.value?.orderStatus === '草稿'
})

const canCopy = computed(() => {
  return true
})

const canSubmit = computed(() => {
  return purchaseOrder.value?.orderStatus === '草稿'
})
const approveDialogVisible = ref(false)
const approveComments = ref('')
const rejectDialogVisible = ref(false)
const rejectReason = ref('')
const rejectToPreviousLevel = ref(false)
const rejectToApplicant = ref(false)

const statusHint = computed(() => {
  if (!purchaseOrder.value) return null

  switch (purchaseOrder.value.orderStatus) {
    case '草稿':
      return {
        title: '草稿状态',
        description: '当前为草稿状态，可以编辑、删除和提交',
        type: 'info'
      }
    case '已提交':
      return {
        title: '已提交',
        description: '订单已提交，等待审批',
        type: 'warning'
      }
    case '待审批':
      return {
        title: '待审批',
        description: '在审批节点还未审批前，可以撤回提交申请，撤回后，可以修改删除提交数据',
        type: 'warning'
      }
    case '审批中':
      return {
        title: '审批中',
        description: '有一个审批人,审批后,审批状态变为审批中,审批中表单,只能进行打印操作',
        type: 'info'
      }
    case '已审批':
      return {
        title: '已审批',
        description: '审批完成后，可以进行入库、到票、付款、退货等操作',
        type: 'success'
      }
    case '驳回':
      return {
        title: '已驳回',
        description: '提交申请被驳回时，在审批记录里查看驳回原因，编辑修改表单，重新提交审批',
        type: 'error'
      }
    case '已完成':
      return {
        title: '已完成',
        description: '订单已完成所有流程',
        type: 'success'
      }
    case '已取消':
      return {
        title: '已取消',
        description: '订单已被取消',
        type: 'info'
      }
    default:
      return null
  }
})

const statusStampText = computed(() => {
  const s = purchaseOrder.value?.orderStatus
  switch (s) {
    case '草稿': return '草稿'
    case '已提交': return '已提交'
    case '待审批': return '待审批'
    case '审批中': return '审批中'
    case '已审批': return '已审批'
    case '驳回': return '已驳回'
    case '已完成': return '已完成'
    case '已取消': return '已取消'
    default: return '—'
  }
})

// 生命周期
onMounted(() => {
  const orderId = route.params.id
  if (orderId) {
    loadPurchaseOrder(Number(orderId))
  }
})

// 方法
const loadPurchaseOrder = async (id: number) => {
  try {
    loading.value = true
    console.log('开始加载采购订单详情，ID:', id)
    const response = await purchaseOrderApi.getPurchaseOrderById(id)
    console.log('API响应:', response)
    
    if (response.code === 200) {
      console.log('响应数据:', response.data)
      purchaseOrder.value = response.data
      console.log('设置到组件的数据:', purchaseOrder.value)
    } else {
      console.error('API返回错误:', response.message)
      ElMessage.error(response.message || '获取采购订单详情失败')
    }
  } catch (error) {
    console.error('加载采购订单详情失败:', error)
    ElMessage.error('加载采购订单详情失败')
  } finally {
    loading.value = false
  }
}

const handleBack = () => {
  router.push('/PurchaseOrderList')
}

const handleEdit = () => {
  formVisible.value = true
}

const handleDelete = () => {
  deleteDialogVisible.value = true
}

const handleCopy = () => {
  if (!purchaseOrder.value) return
  const src = purchaseOrder.value
  const duplicated = {
    ...src,
    id: 0,
    purchaseOrderNumber: '',
    orderStatus: '草稿',
    createdAt: new Date().toISOString(),
    createdByName: src.createdByName,
    details: src.details?.map(d => ({
      ...d,
      id: 0,
      purchaseOrderId: 0
    })) || [],
    attachments: []
  } as any
  purchaseOrder.value = duplicated
  formVisible.value = true
}

const handlePrint = () => {
  try {
    const root = document.querySelector('.purchase-order-detail') as HTMLElement
    if (!root) {
      ElMessage.error('未找到可打印内容')
      return
    }
    const printWindow = window.open('', '_blank')
    if (!printWindow) {
      ElMessage.error('浏览器阻止了打印窗口')
      return
    }

    const styles = `
      <style>
        * { box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans SC', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif; margin: 0; padding: 16px; }
        h2 { margin: 0 0 12px 0; }
        .info-section { margin: 12px 0; padding: 12px; border: 1px solid #ddd; border-radius: 4px; }
        .section-title { font-size: 16px; font-weight: 600; margin-bottom: 8px; }
        table { width: 100%; border-collapse: collapse; }
        th, td { border: 1px solid #ddd; padding: 6px 8px; text-align: left; }
        .page-header, .action-buttons { display: none; }
        @page { size: A4 portrait; margin: 12mm; }
      </style>
    `

    printWindow.document.write('<!DOCTYPE html><html><head><meta charset="utf-8" /><title>采购订单打印</title>' + styles + '</head><body>')
    printWindow.document.write(root.innerHTML)
    printWindow.document.write('</body></html>')
    printWindow.document.close()

    printWindow.onload = () => {
      printWindow.focus()
      printWindow.print()
      printWindow.close()
    }
  } catch (e) {
    console.error('打印失败:', e)
    ElMessage.error('打印失败')
  }
}

// 导出详情为 PDF
async function exportDetailPdf() {
  const area = document.querySelector('.purchase-order-detail') as HTMLElement
  if (!area) {
    ElMessage.error('未找到可导出的区域')
    return
  }
  try {
    const canvas = await html2canvas(area, { scale: 2, useCORS: true, backgroundColor: '#ffffff' })
    const img = canvas.toDataURL('image/png')
    const pdf = new jsPDF('p', 'pt', 'a4')
    const pageWidth = pdf.internal.pageSize.getWidth()
    const pageHeight = pdf.internal.pageSize.getHeight()
    const imgWidth = pageWidth - 40
    const imgHeight = (canvas.height * imgWidth) / canvas.width

    let y = 20
    pdf.addImage(img, 'PNG', 20, y, imgWidth, imgHeight)
    pdf.setFontSize(10)
    pdf.text(`导出时间: ${new Date().toLocaleString()}`, 20, pageHeight - 10)

    const ts = new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-')
    pdf.save(`采购订单-${purchaseOrder.value?.purchaseOrderNumber || ''}-${ts}.pdf`)
    ElMessage.success('PDF 导出成功')
  } catch (e) {
    console.error('详情导出 PDF 失败', e)
    ElMessage.error('详情导出 PDF 失败')
  }
}

const handleSubmit = async () => {
  if (!purchaseOrder.value) return
  const res = await purchaseOrderApi.submitPurchaseOrder(purchaseOrder.value.id)
  if (res.code === 200) {
    ElMessage.success('已提交审批')
    await loadPurchaseOrder(purchaseOrder.value.id)
  } else {
    ElMessage.error(res.message || '提交失败')
  }
}

const testApi = async () => {
  try {
    const orderId = route.params.id
    if (orderId) {
      console.log('测试API调用，ID:', orderId)
      await loadPurchaseOrder(Number(orderId))
    }
  } catch (error) {
    console.error('测试API失败:', error)
  }
}

const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

const handleFormSuccess = () => {
  formVisible.value = false
  // 重新加载数据
  const orderId = route.params.id
  if (orderId) {
    loadPurchaseOrder(Number(orderId))
  }
  ElMessage.success('更新成功')
}

const confirmDelete = async () => {
  if (!purchaseOrder.value) return

  try {
    const response = await purchaseOrderApi.deletePurchaseOrder(purchaseOrder.value.id)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      deleteDialogVisible.value = false
      router.push('/PurchaseOrderList')
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    console.error('删除采购订单失败:', error)
    ElMessage.error('删除采购订单失败')
  }
}

const downloadAttachment = (attachment: any) => {
  ElMessage.info('下载功能开发中...')
}

const deleteAttachment = (attachment: any) => {
  ElMessage.info('删除附件功能开发中...')
}

const previewAttachment = (attachment: any) => {
  ElMessage.info('预览功能开发中...')
}

// 解析分页工具
function parsePaging(data: any) {
  const inner = data || {}
  const pageData = inner.pageData ?? inner.PageData ?? []
  const totalCount = inner.totalCount ?? inner.TotalCount ?? 0
  const pageIndex = inner.pageIndex ?? inner.PageIndex ?? 1
  const pageSize = inner.pageSize ?? inner.PageSize ?? 5
  return { pageData, totalCount, pageIndex, pageSize }
}

async function loadInboundRecords(page?: number) {
  try {
    tabLoading.value = true
    const id = Number(route.params.id)
    if (page) inboundPageIndex.value = page
    const res = await purchaseOrderApi.getInboundRecords(id, inboundPageIndex.value, inboundPageSize.value)
    if (res.code === 200) {
      const { pageData, totalCount } = parsePaging(res.data)
      inboundRecords.value = pageData
      inboundTotal.value = totalCount
    }
  } finally {
    tabLoading.value = false
  }
}

async function loadPaymentRecords(page?: number) {
  try {
    tabLoading.value = true
    const id = Number(route.params.id)
    if (page) paymentPageIndex.value = page
    const res = await purchaseOrderApi.getPaymentRecords(id, paymentPageIndex.value, paymentPageSize.value)
    if (res.code === 200) {
      const { pageData, totalCount } = parsePaging(res.data)
      paymentRecords.value = pageData
      paymentTotal.value = totalCount
    }
  } finally {
    tabLoading.value = false
  }
}

async function loadInvoiceRecords(page?: number) {
  try {
    tabLoading.value = true
    const id = Number(route.params.id)
    if (page) invoicePageIndex.value = page
    const res = await purchaseOrderApi.getInvoiceRecords(id, invoicePageIndex.value, invoicePageSize.value)
    if (res.code === 200) {
      const { pageData, totalCount } = parsePaging(res.data)
      invoiceRecords.value = pageData
      invoiceTotal.value = totalCount
    }
  } finally {
    tabLoading.value = false
  }
}

async function loadInspectionRecords(page?: number) {
  try {
    tabLoading.value = true
    const id = Number(route.params.id)
    if (page) inspectionPageIndex.value = page
    const res = await purchaseOrderApi.getInspectionRecords(id, inspectionPageIndex.value, inspectionPageSize.value)
    if (res.code === 200) {
      const { pageData, totalCount } = parsePaging(res.data)
      inspectionRecords.value = pageData
      inspectionTotal.value = totalCount
    }
  } finally {
    tabLoading.value = false
  }
}

async function loadReturnRecords(page?: number) {
  try {
    tabLoading.value = true
    const id = Number(route.params.id)
    if (page) returnPageIndex.value = page
    const res = await purchaseOrderApi.getReturnRecords(id, returnPageIndex.value, returnPageSize.value)
    if (res.code === 200) {
      const { pageData, totalCount } = parsePaging(res.data)
      returnRecords.value = pageData
      returnTotal.value = totalCount
    }
  } finally {
    tabLoading.value = false
  }
}

async function loadApprovalRecords() {
  try {
    tabLoading.value = true
    const id = Number(route.params.id)
    const res = await purchaseOrderApi.getApprovalRecords(id)
    if (res.code === 200) {
      const data = res.data || {}
      approvalFlowNodes.value = data.flow?.nodes || ['开始', '发起人申请', '审批节点一', '审批节点二', '结果']
      approvalSteps.value = data.steps || []
      approvalActiveIndex.value = (approvalFlowNodes.value?.length || 1) - 2
    }
  } finally {
    tabLoading.value = false
  }
}

async function loadOperationRecords(page?: number) {
  try {
    tabLoading.value = true
    const id = Number(route.params.id)
    if (page) operationPageIndex.value = page
    const res = await purchaseOrderApi.getOperationRecords(id, operationPageIndex.value, operationPageSize.value)
    if (res.code === 200) {
      const { pageData, totalCount } = parsePaging(res.data)
      operationRecords.value = pageData
      operationTotal.value = totalCount
    }
  } finally {
    tabLoading.value = false
  }
}

watch(activeTab, (val) => {
  switch (val) {
    case 'inbound-record':
      loadInboundRecords(1)
      break
    case 'payment-record':
      loadPaymentRecords(1)
      break
    case 'invoice-record':
      loadInvoiceRecords(1)
      break
    case 'inspection-record':
      loadInspectionRecords(1)
      break
    case 'return-record':
      loadReturnRecords(1)
      break
    case 'approval-record':
      loadApprovalRecords()
      break
    case 'operation-record':
      loadOperationRecords(1)
      break
  }
})

// 工具方法
const getStatusType = (status?: string) => {
  switch (status) {
    case '草稿':
      return 'info'
    case '待审批':
      return 'warning'
    case '审批中':
      return 'info'
    case '已完成':
      return 'success'
    case '驳回':
      return 'danger'
    case '已取消':
      return 'info'
    default:
      return 'info'
  }
}

const getStatusText = (status?: string) => {
  if (!status) return '未知'
  return status
}

const getSettlementMethodText = (method?: string) => {
  if (!method) return '-'
  return method
}

const formatDate = (date?: string) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

const formatDateTime = (dateTime?: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

const formatCurrency = (amount: number) => {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY'
  }).format(amount || 0)
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const getDetailSummary = (param: any) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '合计'
    } else if (index === 1) {
      sums[index] = '小计'
    }
  })
  return sums
}

async function confirmApprove() {
  if (!purchaseOrder.value) return
  const res = await purchaseOrderApi.approvePurchaseOrder(purchaseOrder.value.id, approveComments.value)
  if (res.code === 200) {
    ElMessage.success('审批通过')
    approveDialogVisible.value = false
    await loadPurchaseOrder(purchaseOrder.value.id)
  } else {
    ElMessage.error(res.message || '操作失败')
  }
}

async function confirmReject() {
  if (!purchaseOrder.value) return
  const res = await purchaseOrderApi.rejectPurchaseOrder(
    purchaseOrder.value.id,
    rejectReason.value,
    rejectToPreviousLevel.value,
    rejectToApplicant.value
  )
  if (res.code === 200) {
    ElMessage.success('已驳回')
    rejectDialogVisible.value = false
    await loadPurchaseOrder(purchaseOrder.value.id)
  } else {
    ElMessage.error(res.message || '操作失败')
  }
}

const gotoIncomingInspectionList = () => {
  router.push('/IncomingInspectionList')
}
</script>

<style scoped>
.purchase-order-detail {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.header-left h2 {
  margin: 0 0 10px 0;
  color: #303133;
}

.order-title {
  font-size: 18px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 10px;
}

.order-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  font-size: 14px;
  color: #606266;
}

.header-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 15px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-stamp {
  font-size: 18px;
  font-weight: bold;
  color: #67c23a; /* 绿色 */
  background-color: #e1f3d8; /* 浅绿色背景 */
  padding: 8px 16px;
  border-radius: 8px;
  border: 1px solid #e1f3d8;
}

.status-tag {
  font-size: 16px;
  padding: 8px 16px;
}

.status-hint {
  margin-bottom: 20px;
}

.detail-tabs {
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.info-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #fafafa;
}

.section-title {
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.info-item {
  display: flex;
  margin-bottom: 15px;
  align-items: center;
}

.info-item label {
  width: 120px;
  font-weight: 600;
  color: #606266;
  margin-right: 10px;
}

.info-item span {
  color: #303133;
  flex: 1;
}

.detail-actions {
  margin-bottom: 15px;
}

.detail-summary {
  margin-top: 15px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
  display: flex;
  gap: 30px;
}

.summary-item {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.attachment-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.attachment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: white;
}

.attachment-info {
  flex: 1;
}

.file-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 5px;
}

.file-size,
.upload-time {
  font-size: 12px;
  color: #909399;
}

.attachment-actions {
  display: flex;
  gap: 10px;
}

.no-attachments {
  text-align: center;
  padding: 40px;
  color: #909399;
  font-style: italic;
}

.tab-content {
  padding: 20px;
  text-align: center;
  color: #909399;
}

.text-danger {
  color: #f56c6c;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 